import 'package:cave_flutter/pages/whl_chat/whl_chat_room/bottom_controll_view/whl_bottom_control_view_logic.dart';
import 'package:cave_flutter/pages/whl_chat/whl_chat_room/message_items/whl_image_message_item.dart';
import 'package:cave_flutter/pages/whl_chat/whl_chat_room/message_items/whl_text_message_item.dart';
import 'package:cave_flutter/style/whl_style.dart';
import 'package:cave_flutter/utils/extension/string_extension.dart';
import 'package:cave_flutter/utils/whl_date_utils.dart';
import 'package:cave_flutter/utils/whl_user_utils.dart';
import 'package:cave_flutter/whl_app.dart';
import 'package:cave_flutter/widgets/brick/brick.dart';
import 'package:cave_flutter/widgets/refresh_widget.dart';
import 'package:cave_flutter/widgets/whl_app_bar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:nim_core/nim_core.dart';

import '../../../common/chat_manager.dart';
import '../../../widgets/ls_love_progress_view.dart';
import 'bottom_controll_view/whl_bottom_control_view_view.dart';
import 'message_items/call_message_item.dart';
import 'message_items/whl_file_message_item.dart';
import 'message_items/whl_voice_message_item.dart';
import 'whl_chat_room_logic.dart';

class WhlChatRoomPage extends StatefulWidget {
  WhlChatRoomPage({Key? key}) : super(key: key);

  @override
  State<WhlChatRoomPage> createState() => _WhlChatRoomPageState();
}

class _WhlChatRoomPageState extends State<WhlChatRoomPage> with WidgetsBindingObserver {
  final logic = Get.put(WhlChatRoomLogic());

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    super.initState();
  }

  @override
  void didChangeMetrics() {
    WidgetsBinding.instance.addPostFrameCallback((time) {
      if (MediaQuery.of(context).viewInsets.bottom == 0) {
        logic.isShowKeyBoard = false;
      } else {
        logic.isShowKeyBoard = true;
      }
      logic.update(['isShowKeyBoard']);
    });
    super.didChangeMetrics();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: kAppColor('#FDFDFD'),
      appBar: WhlAppBar(
        centerWidget: GetBuilder<WhlChatRoomLogic>(builder: (logic) {
          return UIText(
            margin: EdgeInsets.only(right: 33.w),
            alignment: Alignment.center,
            text: logic.userModel?.remark ?? logic.userModel?.nickName ?? "未知用户",
            textColor: kAppTextColor,
            fontSize: 16.sp,
            fontWeight: FontWeight.bold,
            bottomDrawable: UIText(
              text: '1.9km',
              textColor: kAppColor('#CACACA'),
              fontSize: 13.sp,
            ),
          );
        }),
        rightWidget: UIRow(
          children: [
            LSLoveProgressView(
                width: 32.w, height: 30.w, progress: 0.6, waveHeight: 1, fillColor: kAppColor("#FFEAEF"), color: kAppColor("#FF77A4")),
            UIImage(
              margin: EdgeInsets.only(left: 10.w, right: 20.w, top: 2.w),
              assetImage: 'icon_chat_room_more.png',
              width: 30.w,
              height: 30.w,
              onTap: () {
                logic.doClickMore();
              },
            )
          ],
        ),
      ),
      body: UIColumn(
        children: [
          Expanded(
              child: MediaQuery.removePadding(
            removeTop: true,
            removeBottom: true,
            context: context,
            child: Listener(
              onPointerMove: (event) {
                logic.isShowKeyBoard = false;
                WhlBottomControlViewLogic bottomLogic = Get.find<WhlBottomControlViewLogic>();
                bottomLogic.resetAllStatus();
                hideKeyboard(context);
              },
              onPointerDown: (event) {
                logic.isShowKeyBoard = false;
                WhlBottomControlViewLogic bottomLogic = Get.find<WhlBottomControlViewLogic>();
                bottomLogic.resetAllStatus();
                hideKeyboard(context);
              },
              child: Container(
                decoration: const BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage("assets/images/chat_bg.jpg"),
                    fit: BoxFit.cover,
                  ),
                ),
                // color: kAppColor('#FDFDFD'),
                // color: Colors.red,
                child: MyRefresh(
                  controller: logic.refreshController,
                  // enablePullDown: false,
                  // enablePullUp: true,
                  onLoad: () {
                    logic.onGetMessageList();
                  },
                  child: CustomScrollView(
                    controller: logic.scrollController,
                    reverse: true,
                    shrinkWrap: true,
                    slivers: [
                      GetBuilder<WhlChatRoomLogic>(builder: (logic) {
                        logic.formatMessageDatas();
                        return SliverList(
                            delegate: SliverChildBuilderDelegate((context, index) {
                          NIMMessage message = logic.messageList[index];
                          return buildMessageItem(message);
                        }, childCount: logic.messageList.length));
                      })
                    ],
                  ),
                ),
              ),
            ),
          )),
          WhlBottomControlViewPage(
            isShowKeyBoard: logic.isShowKeyBoard,
            toAccountId: logic.toAccountId,
          ),
        ],
      ),
    );
  }

  buildMessageItem(NIMMessage message) {
    String accountId = ChatManager.getInstance().getImAccountId();
    bool isSend = message.fromAccount == accountId;
    bool needShowTime = message.localExtension?["needShowTime"] ?? false;
    Map<String, dynamic> msgExt = message.remoteExtension ?? {};
    String avatarUrl = msgExt["avatar"] ?? "";
    List<Widget> widgetList = [
      UIImage(
        httpImage: (isSend ? WhlUserUtils.getAvatar() : avatarUrl).toImageUrl(),
        assetPlaceHolder: 'icon_app_logo.png',
        width: 44.w,
        height: 44.w,
        radius: 22.w,
        fit: BoxFit.cover,
      ),
      SizedBox(width: 10.w),
      buildMessageTypeItem(message),
      SizedBox(width: 12.w),
      if (isSend && message.status == NIMMessageStatus.sending)
        UIContainer(
          alignment: Alignment.center,
          margin: EdgeInsets.only(bottom: 15.h),
          child: CupertinoActivityIndicator(
            color: kAppMainColor,
          ),
        ),
      if (isSend && message.status == NIMMessageStatus.success ||
          message.status == NIMMessageStatus.read ||
          message.status == NIMMessageStatus.unread)
        UIText(
          margin: EdgeInsets.only(bottom: 15.h),
          alignment: Alignment.center,
          text: message.isRemoteRead == true ? '已读' : '未读',
          textColor: message.isRemoteRead == true ? kAppColor('#C1C1C1') : kAppSubTextColor,
          fontSize: 13.sp,
        )
      // Visibility(
      //   visible: model.sentStatus == RCIMIWSentStatus.sending,
      //   child: UIColumn(
      //     margin: EdgeInsets.only(bottom: 15.h),
      //     mainAxisAlignment: MainAxisAlignment.center,
      //     children: [
      //       SizedBox(
      //         width: 40.w,
      //         height: 40.w,
      //         child: CupertinoActivityIndicator(
      //           color: kAppSub2TextColor,
      //           radius: 8.w,
      //         ),
      //       ),
      //     ],
      //   ),
      // ),
      // Visibility(
      //   visible: model.sentStatus == RCIMIWSentStatus.failed,
      //   child: UIColumn(
      //     margin: EdgeInsets.only(bottom: 15.h),
      //     mainAxisAlignment: MainAxisAlignment.center,
      //     children: [
      //       SizedBox(
      //         width: 40.w,
      //         height: 40.w,
      //         child: Icon(
      //           Icons.error,
      //           color: Colors.red,
      //           size: 30.w,
      //         ),
      //       ),
      //     ],
      //   ),
      // ),
    ];
    return Column(
      children: [
        if (needShowTime)
          UIText(
            margin: EdgeInsets.only(bottom: 17.h),
            text: WhlDateUtils.getTimeStringFromWechat(message.timestamp, isShowTime: true),
            fontSize: 11.sp,
            textColor: kAppSub2TextColor,
          ),
        IntrinsicHeight(
          child: UIRow(
            crossAxisAlignment: CrossAxisAlignment.start,
            padding: EdgeInsets.symmetric(horizontal: 14.w),
            mainAxisAlignment: isSend ? MainAxisAlignment.end : MainAxisAlignment.start,
            children: isSend ? widgetList.reversed.toList() : widgetList,
          ),
        ),
      ],
    );
  }

  /// 聊天气泡
  buildMessageTypeItem(NIMMessage message) {
    if (message.messageType == NIMMessageType.text) {
      return WhlTextMessageItem(
        message: message,
      );
    } else if (message.messageType == NIMMessageType.audio) {
      return WhlVoiceMessageItem(message: message);
    } else if (message.messageType == NIMMessageType.image) {
      return WhlImageMessageItem(message: message);
    } else if (message.messageType == NIMMessageType.file) {
      return WhlFileMessageItem(message: message);
    } else if (message.messageType == NIMMessageType.custom) {
      Map<String, dynamic>? a = message.messageAttachment?.toMap();
      int customType = a?["customType"] ?? 0;
      if (customType == MyCustomMsgType.videoCall.tag || customType == MyCustomMsgType.audioCall.tag) {
        return CallMessageItem(message: message);
      }
    }

    return Container();
  }
}
